<?php
 
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');
require_once(DOKU_INC.'inc/infoutils.php');
 
class syntax_plugin_lilypond extends DokuWiki_Syntax_Plugin {
 
    function getInfo(){
        return array(
            'author' => 'Sebastian Menge',
            'email'  => 'bastl@users.sf.net',
            'date'   => '2008-09-25',
            'name'   => 'Lilypond Plugin',
            'desc'   => 'Testing 1, 2, 3 ...',
            'url'    => 'http://www.dokuwiki.org/wiki:plugins',
        );
    }
 
    function getType(){
        return 'substition';
    }
 
    function getSort(){
        return 999;
    }
 
 
    function connectTo($mode) {
      $this->Lexer->addEntryPattern('<lilypond>',$mode,'plugin_lilypond');
    }
 
    function postConnect() {
      $this->Lexer->addExitPattern('</lilypond>','plugin_lilypond');
    }
 
 
    function handle($match, $state, $pos, &$handler){
      global $ID;
      if ( $state == DOKU_LEXER_UNMATCHED ) {

        $filename = DOKU_INC.'data/media/'.$ID;

				$this->lilypond($match,$filename);
				$pages = $this->pages($filename.'.pdf');
				$this->writely($filename.'.ly',$match);

        return array($state,$pages);
      }
      return false;
            
    }


    function render($mode, &$renderer, $data) {
				global $ID;
        if($mode == 'xhtml'){
            list($state, $pages) = $data;
            switch ($state) {
              case DOKU_LEXER_ENTER :      
              case DOKU_LEXER_UNMATCHED : 
              case DOKU_LEXER_EXIT :     
								$baseurl = ml($ID);

								//render thumbnails
								if ( $pages == 1) {
										$renderer->doc.='<a href="'.ml($ID).".png\"><img class=\"\" border=\"2\" src=\"".ml($ID).".png\"/></a>";
								} else {
									for ($i = 1; $i<=$pages; $i++) {
										$renderer->doc.='<a href="'.ml($ID)."-page$i.png\"><img class=\"\" border=\"2\" src=\"".ml($ID)."-page$i.png\"/></a>";
									}
								}
								$renderer->doc .= '<hr>';

								//render download links 
								$link ='<a href="'.$baseurl.'.pdf" class="media mediafile mf_pdf" title="'.$ID.'.pdf">'.$ID.'.pdf</a>';
								$renderer->doc .= $link;

								$link ='<a href="'.$baseurl.'.ly" class="media mediafile mf_txt" title="'.$ID.'.ly">'.$ID.'.ly</a>';
								$renderer->doc .= $link;
								$renderer->doc .= '<hr>';

								$renderer->doc.='<p>'.$pages.'pages of output</p>';
								break; 
            }
            return true;
        }
        return false;
    }

////////////////////   Helper     //////////////////////
	

/**
 * pipe some string into lilypond and write png and pdf output 
 * to data/media
 **/
function lilypond($string,$basename) {

  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("file", "/tmp/plugin_lilypond.log", "a") // stderr is a file to write to
  );

  $cwd = DOKU_INC.'data/media';
  $env = array('some_option' => 'aeiou');
  
	$rawcmd = '/usr/bin/lilypond --png --pdf -dresolution=20 -ddelete-intermediate-files=#t';
  $cmd = $rawcmd.' -o '.$basename.' -';
  
  $fp = fopen('/tmp/plugin_lilypond.log', 'a');
  fwrite($fp, 'about to call lilypond: '.$cmd);
  fclose($fp);

  $process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env);
  
  if (is_resource($process)) {
      // $pipes now looks like this:
      // 0 => writeable handle connected to child stdin
      // 1 => readable handle connected to child stdout
      // Any error output will be appended to /tmp/error-output.txt
  
      fwrite($pipes[0], $string);
      fclose($pipes[0]);

  
      // echo stream_get_contents($pipes[1]);
      fclose($pipes[1]);
  
      // It is important that you close any pipes before calling
      // proc_close in order to avoid a deadlock
      $return_value = proc_close($process);
  
      // echo "command returned $return_value\n";
  }
}

function writely($file,$string) {
  $fp = fopen($file, 'w');
  fwrite($fp, $string);
  fclose($fp);
}

function pages($file) {
  $output = array();
	exec( "/usr/bin/pdfinfo $file | grep 'Pages: '",$output);
	$lines = split(':',$output[0]);
	return trim($lines[1]);
}

}
 
//Setup VIM: ex: ts=2 sts enc=utf-8 :
?>
